﻿using System.Collections.Generic;
using System.Data.SqlClient;
using Microsoft.SqlServer.Management.Common;
using Microsoft.SqlServer.Management.Smo;

namespace eAtlantida.Tools.Generator.Sql
{
    /// <summary>
    /// Get database schema
    /// </summary>
    public class Discover
    {
        private readonly string _connectionString;

        /// <summary>
        /// Initializes a new instance of the <see cref="Discover" /> class.
        /// </summary>
        /// <param name="connectionString">The connection string.</param>
        public Discover(string connectionString)
        {
            _connectionString = connectionString;
        }

        /// <summary>
        /// Gets the tables.
        /// </summary>
        public List<string> GetTables()
        {
            var result = new List<string>();
            using (var sqlConnection = new SqlConnection(_connectionString))
            {
                var server = new Server(new ServerConnection(sqlConnection));
                var database = new Database(server, sqlConnection.Database);
                database.Refresh();
                foreach (Table table in database.Tables)
                {
                    table.Refresh();
                    result.Add(table.Name);
                }
            }
            return result;
        }

        /// <summary>
        /// Gets the columns.
        /// </summary>
        /// <param name="tableName">Name of the table.</param>
        public IEnumerable<ColumnInformation> GetColumns(string tableName)
        {
            var result = new List<ColumnInformation>();
            using (var sqlConnection = new SqlConnection(_connectionString))
            {
                var server = new Server(new ServerConnection(sqlConnection));
                var database = new Database(server, sqlConnection.Database);
                database.Refresh();
                var table = new Table(database, tableName);
                table.Refresh();
                foreach (Column column in table.Columns)
                {
                    var value = new ColumnInformation
                        {
                            Name = column.Name,
                            DataTypeName = column.DataType.Name,
                            IsIdentity = column.Identity,
                            IsPrimaryKey = column.InPrimaryKey
                        };
                    if (value.DataTypeName == "nvarchar")
                    {
                        value.DataTypeName = value.DataTypeName + "(" + column.DataType.MaximumLength + ")";
                    }
                    result.Add(value);
                }
            }
            return result;
        }
    }
}